<template>
	<div class="login">
		<van-form @submit="onSubmit">
			<h1>登录</h1>
			<van-field
				v-model="userName"
				name="userName"
				label="用户名"
				placeholder="用户名"
				:rules="[{ required: true, message: '请填写用户名' }]"
			/>
			<van-field
				v-model="password"
				type="password"
				name="password"
				label="密码"
				placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' }]"
			/>
			<div style="margin: 16px">
				<van-button round block type="info" native-type="submit"
					>登录</van-button
				>
			</div>
		</van-form>
	</div>
</template>

<script>
import { reqLogin } from "@/api/user";
import { setToken } from "@/utils/auth";
import { Notify } from "vant";
export default {
	data() {
		return {
			userName: "",
			password: "",
		};
	},
	computed: {},
	watch: {},

	methods: {
		async onSubmit(values) {
			console.log("submit", values);
			// 获取表单的参数
			let data = { ...values };
			// 调用封装的登录接口
			const res = await reqLogin(data);
			console.log(res);
			if (res.code == "success") {
				// 成功通知;
				Notify({ type: "success", message: "登陆成功", duration: 1000 });
				// 将获取的token存入cookie中一份
				this.$store.commit("token/changeToken", res.token);
				// 存到本地存储里面，因为vuex刷新后会消失，在App.vue中做持久化处理
				localStorage.setItem("token", res.token);
				setToken(res.token);
				// 存入vuex一份
				// 登陆成功跳转到首页。
				this.$router.push("/home");
			}
		},
	},
	created() {},
	mounted() {},
	components: {},
};
</script>
<style scoped>
h1 {
	text-align: center;
	font-size: 30px;
	line-height: 50px;
}
form .van-cell {
	margin: 10px;
}
</style>
